<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>{{ $route.query.type == "add" ? '新增用户' : "编辑用户" }}</span>
        <el-button type="primary" :loading="buttonLoading" @click="router.push('/UserManager/Index')">退出</el-button>
      </div>
    </template>

    <div class="add-form" v-loading="loading">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        label-position="left"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="用户名" prop="loginName">
          <el-input v-model="ruleForm.loginName" placeholder="请输入用户名" :disabled="$route.query.type == 'edit'"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="passWord" v-if="$route.query.type == 'add'">
          <el-input v-model="ruleForm.passWord" placeholder="请输入密码，默认初始密码，123456" show-password></el-input>
        </el-form-item>

        <el-form-item label="在职状态" prop="jobState">
          <el-select v-model="ruleForm.jobState" placeholder="请选择在职状态">
            <el-option label="在职" :value="1" />
            <el-option label="离职" :value="0" />
          </el-select>
        </el-form-item>

        <el-form-item label="姓名" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入用户姓名"></el-input>
        </el-form-item>

        <el-form-item label="工号" prop="jobNumber">
          <el-input v-model="ruleForm.jobNumber" placeholder="请输入工号"></el-input>
        </el-form-item>

        <el-form-item label="部门" prop="orgId">
          <el-cascader
            v-model="ruleForm.orgId"
            :options="departList"
            :show-all-levels="false"
            :props="cascaderProps"
            ref="departmentRef"
            @change="orgChange"
          />
        </el-form-item>

        <el-form-item label="职位" prop="jobTitle">
          <el-input v-model="ruleForm.jobTitle" placeholder="请输入职位"></el-input>
        </el-form-item>

        <el-form-item label="省份" prop="province">
          <el-input v-model="ruleForm.province" placeholder="请输入省份"></el-input>
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-select v-model="ruleForm.gender" placeholder="请选择性别">
            <el-option label="男" :value="1" />
            <el-option label="女" :value="2" />
            <el-option label="未知" :value="3" />
          </el-select>
        </el-form-item>

        <el-form-item label="生日" prop="birthDate">
          <el-date-picker
            v-model="ruleForm.birthDate"
            type="date"
            placeholder="请选择生日"
            value-format="YYYY-MM-DD"
            clearable
          />
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="ruleForm.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>

        <el-form-item label="邮箱地址" prop="email">
          <el-input v-model="ruleForm.email" placeholder="请输入邮箱地址"></el-input>
        </el-form-item>

        <el-form-item label="账号状态" prop="status">
          <el-select v-model="ruleForm.status" placeholder="请选择账号状态">
            <el-option label="正常" :value="1" />
            <el-option label="无效" :value="0" />
          </el-select>
        </el-form-item>

        <el-form-item label="角色" prop="roleList">
          <el-checkbox-group v-model="ruleForm.roleList">
            <el-checkbox v-for="(item, index) in roleList" :key="index" :label="`${item.id}_${item.name}`">
              {{ item.name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        
        <div class="add-button">
          <el-button type="primary" @click="submitForm(ruleFormRef)" :loading="buttonLoading">
            {{ $route.query.type == "add" ? '新增' : "编辑" }}
          </el-button>
          <el-button @click="resetForm(ruleFormRef)" :loading="buttonLoading">重置</el-button>
        </div>
      </el-form>
    </div>
  </el-card>
</template>

<script>
export default { name: "addUser" }
</script>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router'
import { UploadFilled, Picture } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { http } from '@/utils/http/index';
import { uploadFile } from '@/utils/file.js'
import { ContentTypeEnum } from '@/enums/httpEnum';
import { arrayToTree } from "@/utils/index.js"

/* 路由 */
const router = useRouter()

onMounted(() => {
  getDepartList()
  getRoleList()
  if(router.currentRoute.value.query.id){
    getUserDetail()
  }
})

/* 详情数据加载动画 */
const loading = ref(false)

/* 查询详情 */
const getUserDetail = () => {
  loading.value = true
  http.$GET("/UserManager/GetUserById", { Id: router.currentRoute.value.query.id }).then(res => {
    loading.value = false
    if (res.isError) return ElMessage.warning("查询用户详情失败")
    if (!res.result) return
    
    /* 赋值 */
    Object.keys(ruleForm.value).forEach((key)=>{
      if(res.result.content.user[key] != null){
        ruleForm.value[key] = res.result.content.user[key];
      }
    })
    fullForm.value = res.result.content.user

    /* 角色赋值 */
    if(res.result.content.roles.length) {
      res.result.content.roles.forEach((item) => {
        ruleForm.value.roleList.push(`${item.id}_${item.name}`)
      })
    }
  }).catch(err => {
    loading.value = false
    ElMessage.warning("查询用户详情失败")
  })
}

/* 组织列表 */
const departList = ref([])

/* 组织级联选择器配置 */
const cascaderProps = ref({
  label: "text",
  value: "id",
  children: 'children',
  checkStrictly: true,
})

/* 组织级联选择器 */
const departmentRef = ref(null)

/* 级联选择器选择 */
const orgChange = (value) => {
  getOrgDetail(value[value.length - 1])
}

/* 查询组织详情 */
const getOrgDetail = (id) => {
  http.$GET("/OrgManager/GetOrgById", { id: id }).then(res => {
    if(res.isError) return ElMessage.warning(res.message)
    ruleForm.value.orgName = res.result.content.org.orgName
  })
}

/* 获取组织树列表 */
const getDepartList = () => {
  http.$GET("/OrgManager/GetOrgInfo").then(res => {
    if(res.isError) return ElMessage.warning(res.message)
    if( !res.Result.data.length ) return
    departList.value = arrayToTree(res.Result.data)
  }).catch(() => {
    ElMessage.warning('查询组织列表失败')
  })
}

/* 角色列表 */
const roleList = ref([])
const rolePageNum = ref(1)
const rolePageSize = ref(100)

/* 获取角色列表 */
const getRoleList = () => {
  let params = {
    pagenum: rolePageNum.value,
    pagesize: rolePageSize.value
  }
  http.$GET("/RoleManager/GetRole", params).then(res => {
    if(res.isError) return ElMessage.warning('查询角色列表失败')
    if(!res.result.content.length) return

    /* 所有角色 */
    roleList.value = roleList.value.concat(res.result.content)
    if(rolePageNum.value < res.result.total_num) {
      rolePageNum.value = rolePageNum.value + 1
      getRoleList()
    }
  }).catch(() => {
    ElMessage.warning('查询角色列表失败')
  })
}

/* 新增、编辑表单 */
const ruleFormRef = ref(null)

const fullForm = ref({})

/* 新增、编辑表单数据 */
const ruleForm = ref({
  id: "",
  status: 1,
  jobState: 1,
  name: "",
  jobNumber: "",
  orgId: "",
  orgName: "",
  jobTitle: "",
  province: "",
  gender: "",
  birthDate: "",
  phone: "",
  email: "",
  loginName: "",
  passWord: "",
  roleList: [],
})

/* 上传文件校验 */
const checkPhone = (rule, value, callback) => {
  // 判断手机号格式是否正确  
  const regex = /^1[3-9]\d{9}$/; // 中国手机号的正则表达式  
  if (!regex.test(value)) {
    callback(new Error('请输入正确格式的电话号码'))
  }
  callback()
}

const checkEmail = (rule, value, callback) => {
  const regEmail=/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
  if (ruleForm.value.email) {
    if (!regEmail.test(ruleForm.value.email)) {
      callback(new Error('请输入正确格式的邮件地址'))
    } else {
      callback()
    }
  } else {
    callback()
  }
}

/* 表单校验规则 */
const rules = reactive({
  status: [
    { required: true, message: '请选择账号状态', trigger: 'change' }
  ],
  jobState: [
    { required: true, message: '请选择在职状态', trigger: 'change' }
  ],
  name: [
    { required: true, message: '请填写用户姓名', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  orgId: [
    { required: true, message: '请选择组织部门', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入电话号码', trigger: 'blur' },
    { message: '请输入正确格式的电话号码', trigger: 'blur', validator: checkPhone }
  ],
  email: [
    { message: '请输入正确格式的邮箱地址', trigger: 'blur', validator: checkEmail }
  ],
  loginName: [
    { required: true, message: '请填写用户名', trigger: 'blur' }
  ],
  roleList: [
    { required: true, message: '请至少选择一个角色', trigger: 'blur' }
  ],
})

/* 提交新增或编辑时，按钮禁用 */
const buttonLoading = ref(false)

/* 提交 */
const submitForm = (formName) => {
  ruleFormRef.value.validate((valid, fields) => {
    if(valid) {
      buttonLoading.value = true

      let params = JSON.parse(JSON.stringify(ruleForm.value))

      /* 处理密码字段 */
      if(router.currentRoute.value.query.type == 'add' && !params.passWord) {
        params.passWord = 123456
      }

      /* 处理角色字段 */
      if( params.roleList && params.roleList.length ){
        params.roles = params.roleList.join(",")
      }

      /* 处理组织字段 */
      if( params.orgId.length && typeof(params.orgId) == 'object' ) {
        params.orgId = params.orgId[params.orgId.length - 1]
      }

      const formData = new FormData()
      for(let k in params) {
        if( k != "roleList")
        formData.append(k ,params[k])
      }

      http.$POST("/UserManager/AddOrUpdateUser", formData).then(res => {
        buttonLoading.value = false
        if (res.isError) {
          ElMessage.warning(res.message);
        }else{
          ElMessage.success('操作成功');
          router.push({
            path: "/UserManager/Index"
          })
        }
      }).catch(err => {
        buttonLoading.value = false
        ElMessage.warning('操作失败');
      })
    }else{
      ElMessage.warning('请先完成必填项');
    }
  })
}

/* 重置 */
const resetForm = (formName) => {
  ruleFormRef.value.resetFields()
  ruleForm.value.status = ""
  ruleForm.value.jobState = ""
  ruleForm.value.loginName = fullForm.value.loginName
}
</script>

<style lang='scss' scoped>
@import "@/assets/styles/backendElement.scss";
</style>